package com.open.capacity.employee.service.impl;

import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.FileInfo;

import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.util.ValidatorUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;

import com.open.capacity.employee.dao.EmpinformationDao;
import com.open.capacity.employee.dao.SysUserRoleDao;
import com.open.capacity.employee.feign.FileFeign;
import com.open.capacity.employee.model.EmployeeModel;
import com.open.capacity.employee.model.Information;
import com.open.capacity.employee.model.InformationModel;
import com.open.capacity.employee.service.EmpinformationService;
import com.open.capacity.employee.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Slf4j
@Service
public class EmpinformationImpl implements EmpinformationService {

    @Autowired
    private EmpinformationDao empinformationDao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private SysUserRoleDao userRoleDao;

    @Autowired(required = false)
    private TokenStore redisTokenStore;

    @Autowired
    private FileFeign fileFeign;

    @Override
    @Transactional
    public void addSysUser(Information information) throws ServiceException {
        try {
            String fullName = information.getFullName();
            if (StringUtils.isBlank(fullName)) {
                throw new IllegalArgumentException("用户名不能为空");
            }

            if (ValidatorUtil.checkPhone(fullName)) {// 防止用手机号直接当用户名，手机号要发短信验证
                throw new IllegalArgumentException("用户名要包含英文字符");
            }

            if (fullName.contains("@")) {// 防止用邮箱直接当用户名，邮箱也要发送验证（暂未开发）
                throw new IllegalArgumentException("用户名不能包含@");
            }

            if (fullName.contains("|")) {
                throw new IllegalArgumentException("用户名不能包含|字符");
            }

            Information persistenceUser = empinformationDao.findByUsername(information.getFullName());
            if (persistenceUser != null && persistenceUser.getFullName() != null) {
                throw new IllegalArgumentException("用户名已存在");
            }
            information.setCreateTime(new Date());
            empinformationDao.save(information);
            log.info("添加用户：{}", information);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public Result picture(MultipartFile file) throws ServiceException {
        try {
            FileInfo picture = fileFeign.picture(file);
            if (picture != null) {
                return Result.succeed(picture, "操作成功");
            } else {
                return Result.failed("操作失败");
            }
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public Information findById(Long id) throws ServiceException {
        return null;
    }

    @Override
    public Result updatePassword(Long id, String oldPassword, String newPassword) throws ServiceException {
        return null;
    }

    @Override
    public Information updateSysUser(Information information) throws ServiceException {
        return null;
    }

    @Override
    public PageResult<Information> findUsers(Map<String, Object> params) throws ServiceException {
        try {
            int total = empinformationDao.count(params);
            List<Information> list = Collections.emptyList();
            if (total > 0) {
                PageUtil.pageParamConver(params, true);
                list = empinformationDao.findList(params);
            }
            return PageResult.<Information>builder().data(list).code(0).count((long) total).build();
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public Result updateEnabled(Map<String, Object> params) throws ServiceException {
        return null;
    }

    @Override
    @Transactional
    public Result saveOrUpdate(Information information) throws ServiceException {
        try {
            String fullName = information.getFullName();
            if (StringUtils.isBlank(fullName)) {
                //throw new IllegalArgumentException("用户名不能为空");
                return Result.failed("用户名不能为空");
            }

            if (ValidatorUtil.checkPhone(fullName)) {// 防止用手机号直接当用户名，手机号要发短信验证
                //throw new IllegalArgumentException("用户名要包含英文字符");
                return Result.failed("用户名要包含英文字符");
            }

            if (fullName.contains("@")) {// 防止用邮箱直接当用户名，邮箱也要发送验证（暂未开发）
                //throw new IllegalArgumentException("用户名不能包含@");
                return Result.failed("用户名不能包含@");
            }

            if (fullName.contains("|")) {
                //throw new IllegalArgumentException("用户名不能包含|字符");
                return Result.failed("用户名不能包含|字符");
            }
            if (!StringUtils.isBlank(information.getPhone())) {

                if (!ValidatorUtil.checkPhone(information.getPhone())) {// 防止用手机号直接当用户名，手机号要发短信验证
                    //throw new IllegalArgumentException("用户名要包含英文字符");
                    return Result.failed("手机号格式不正确");
                }

            }
            information.setStatus(Boolean.TRUE);
            information.setCreateTime(new Date());

            int i = 0;

            if (information.getId() == null) {
                Information persistenceUser = empinformationDao.findByUsername(information.getFullName());
                if (persistenceUser != null && persistenceUser.getFullName() != null) {
                    //throw new IllegalArgumentException("用户名已存在");
                    return Result.failed("用户名已存在");
                }
//                information.setUpdateTime(information.getCreateTime());
                information.setUpdateTime(information.getCreateTime());
                i = empinformationDao.insert(information);
            } else {
//                information.setUpdateTime(new Date());
                i = empinformationDao.updateByPrimaryKey(information);
            }
            return i > 0 ? Result.succeed(information, "操作成功") : Result.failed("操作失败");
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public List<InformationModel> findAllUsers(Map<String, Object> params) throws ServiceException {
        try {
            List<InformationModel> informationModels = new ArrayList<>();
            List<Information> list = empinformationDao.findList(params);

            for (Information Information : list) {
                InformationModel informationModel = new InformationModel();
                BeanUtils.copyProperties(Information, informationModel);
                informationModels.add(informationModel);
            }
            return informationModels;
        } catch (BeansException e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public void deleteUser(Long id) throws ServiceException {

    }
}
